#include <stdlib.h>
#include <GL/glut.h>
#include <assert.h>
#include "../ResourceManagers/TextureManager.hpp"
#include "../Extensions/ExtensionsLoader.hpp"
#include "MaskedSprite.hpp"

using namespace std;

MaskedSprite::MaskedSprite(string name, string maskName, MVector3D &origin, TexType eTextureType, float fScale) 
: Sprite(name, origin, fScale)
{
	assert(eTextureType != TEXTURE_ALPHA); //Masked sprite should use TEXTURE_STANDARD!

	m_maskName = maskName;
	TextureManager::GetInstance()->LoadTexture(m_maskName);
}

MaskedSprite::~MaskedSprite()
{
	TextureManager::GetInstance()->UnloadTexture(m_maskName);
}

void MaskedSprite::Update()
{

}

void MaskedSprite::Render()
{
	//! Enable blending to mask unwanted parts of sprite.
	glEnable(GL_BLEND);
	glDisable(GL_DEPTH_TEST);

	glBlendFunc(GL_DST_COLOR, GL_ZERO);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, ((TextureObject*)(TextureManager::GetInstance()->GetTexture(m_maskName)))->GetTextureID());
	ExtensionsLoader::glActiveTextureARB(GL_TEXTURE0_ARB);

	glBegin(GL_QUADS);

	//! left-top
	glTexCoord2f(0.0, 1.0);
	glVertex3f(m_origin.x - 0.5*m_fScaleX + m_translation.x,
		       m_origin.y + m_translation.y,
			   m_origin.z - 0.5*m_fScaleZ + m_translation.z );

	//! left-bottom
	glTexCoord2f(0.0, 0.0);
	glVertex3f(m_origin.x - 0.5*m_fScaleX + m_translation.x,
		       m_origin.y + m_translation.y,
			   m_origin.z + 0.5*m_fScaleZ + m_translation.z );

	//! right-bottom
	glTexCoord2f(1.0, 0.0);
	glVertex3f(m_origin.x + 0.5*m_fScaleX + m_translation.x,
		       m_origin.y + m_translation.y,
			   m_origin.z + 0.5*m_fScaleZ + m_translation.z );

	//! right-top
	glTexCoord2f(1.0, 1.0);
	glVertex3f(m_origin.x + 0.5*m_fScaleX + m_translation.x,
		       m_origin.y + m_translation.y,
			   m_origin.z - 0.5*m_fScaleZ + m_translation.z );

	glEnd();
	glDisable(GL_TEXTURE_2D);


	glBlendFunc(GL_ONE, GL_ONE);
	Sprite::render();

	//! Disable blending for normal rendering for the rest of the scene.
	glEnable(GL_DEPTH_TEST);
	glDisable(GL_BLEND);
}